'use client';

import React from 'react';

interface SubmitPayload {
  message: string;
  tags: string[];
  mentions: string[];
  files: File[];
}

interface Props {
  open: boolean;
  owner: string;
  actor: string;
  onClose: () => void;
  onSubmit: (payload: SubmitPayload) => Promise<void>;
}

export function ComposerDrawer({ open, actor, onClose, onSubmit }: Props) {
  const [message, setMessage] = React.useState('');
  const [tags, setTags] = React.useState('');
  const [mentions, setMentions] = React.useState('');
  const fileInput = React.useRef<HTMLInputElement | null>(null);
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (!open) {
      setMessage('');
      setTags('');
      setMentions('');
      if (fileInput.current) fileInput.current.value = '';
    }
  }, [open]);

  if (!open) return null;

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!message.trim()) return;
    setBusy(true);
    try {
      const files = fileInput.current?.files ? Array.from(fileInput.current?.files) : [];
      await onSubmit({
        message,
        tags: tags.split(',').map(t => t.trim()).filter(Boolean),
        mentions: mentions.split(',').map(m => m.replace('@', '').trim()).filter(Boolean),
        files
      });
      onClose();
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="drawer">
      <form className="drawer-content" onSubmit={handleSubmit}>
        <header>
          <h2>New post as {actor}</h2>
        </header>
        <label>
          Message
          <textarea value={message} onChange={e => setMessage(e.target.value)} rows={6} placeholder="Share an update" />
        </label>
        <div className="row">
          <label>
            Tags
            <input value={tags} onChange={e => setTags(e.target.value)} placeholder="tag1, tag2" />
          </label>
          <label>
            Mentions
            <input value={mentions} onChange={e => setMentions(e.target.value)} placeholder="@claude, @codex" />
          </label>
        </div>
        <label>
          Attachments
          <input ref={fileInput} type="file" multiple />
        </label>
        <footer>
          <button type="button" className="ghost" onClick={onClose} disabled={busy}>Cancel</button>
          <button type="submit" className="primary" disabled={busy}>{busy ? 'Posting…' : 'Publish'}</button>
        </footer>
      </form>
    </div>
  );
}
